package org.esk.dablog.dao.hibernate;

import org.esk.dablog.dao.AuthorDAO;
import org.esk.dablog.model.Author;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * This class implements Author DAO
 * User: jc
 * Date: 01.12.2006
 * Time: 16:31:03
 * $Id:$
 */
public class AuthorDAOImpl extends HibernateDaoSupport implements AuthorDAO {

    /**
     * @param username
     * @return
     */
    public Author getAuthorByUsername(String username) {
        List result = getHibernateTemplate().find("from " + Author.class.getName() +
                " a where a.username = ?", username);
        return (Author) ((result == null || result.isEmpty()) ? null : result.get(0));
    }

    /**
     * @param a
     * @return
     */
    public long saveAuthor(Author a) {
        getHibernateTemplate().saveOrUpdate(a);
        return a.getId();
    }

    /**
     * returns list of last registered users
     *
     * @param usersCount
     * @return
     */
    public List listLastRegisteredUsers(int usersCount) {
        getHibernateTemplate().setMaxResults(usersCount);
        List result = getHibernateTemplate().find(" from " + Author.class.getName() +
                " a where a.blocked = 0 order by a.registerDate desc");
        getHibernateTemplate().setMaxResults(0);
        return result;
    }

    /**
     * returns author by id
     * @param id
     * @return
     */
    public Author getAuthorById(long id) {
        return (Author) getHibernateTemplate().get(Author.class, id);
    }
}
